<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cartInfo in cartInfoList" :key="cartInfo.id">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="!!cartInfo.isChecked" @change="checkCartInfoState(cartInfo)" />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl">
            <div class="item-msg"> {{cartInfo.skuName}}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{cartInfo.skuPrice}}.00</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="changeSkuNum('decrement', cartInfo)">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" minnum="1" class="itxt" @change="changeSkuNum('change', cartInfo, $event)">
            <a href="javascript:void(0)" class="plus" @click="changeSkuNum('increment', cartInfo)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{cartInfo.skuPrice * cartInfo.skuNum}}</span>
          </li>
          <li class="cart-list-con7">
            <a href="javascript:;" class="sindelet" @click="showDialogByDelOneCartInfo(cartInfo.skuId)">删除</a>
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>

      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="showDialogByDelSelected">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{ selectedCount }}</span>件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{selectedMoney}}</i>
        </div>
        <div class="sumbtn">
          <router-link to="/trade" class="sum-btn">结算</router-link>
        </div>
      </div>
    </div>

    <!-- 使用Dialog弹框 -->
    <Dialog :visible.sync="visible">
      <template v-slot:header> <span>提示</span> </template>
      <template>
        <p>你真的要删除{{ isDelOne ? "这条" : "这些选中的" }}数据吗？</p>
      </template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn btn-cancle" @click="visible=false">取消</button>
          <button class="btn btn-primary" @click="delShopCartInfo">确认</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import { debounce } from '../../utils/debounce';
import { skuNumReg } from '@/utils/reg';
import { reqShopCartListData, reqChangeShopCartInfoState, reqChangeAllCartState, reqDelOneShopCartInfo, reqDelSelectedCartInfo, reqAddOrUpdateCart } from '@/api';
export default {
  name: 'ShopCart',
  data() {
    return {
      cartInfoList: [],
      visible: false,
      skuId: '',
      isDelOne: false,
      skuIdList: [], // 存储批量删除被选中的商品时的skuId
      leftCartInfoList: [], // 剩余未删除的商品
      timeId: null,
      num: 0
    };
  },
  async mounted() {
    const result = await reqShopCartListData();
    // console.log('shopcart', result);
    if (result.code === 200) {
      console.log(result);
      this.cartInfoList = result.data[0].cartInfoList;
    } else {
      console.log(result.message);
    }
  },
  methods: {
    async checkCartInfoState(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked;
      const result = await reqChangeShopCartInfoState(cartInfo.skuId, isChecked);
      // 更新服务器数据成功后，重新更新页面
      cartInfo.isChecked = isChecked;
    },
    showDialogByDelOneCartInfo(skuId) {
      // 2.1 弹出对话框
      this.visible = true;
      // 2.2 收集要删除商品的skuId
      this.skuId = skuId;
      this.isDelOne = true; // 是删除一条商品吗
    },
    // 3. 单击弹出框的确定按钮 删除一条商品数据
    async delShopCartInfo() {
      if (this.isDelOne) {
        // 删除一条商品
        const result = await reqDelOneShopCartInfo(this.skuId);
        if (result.code === 200) {
          this.visible = false; // 隐藏对话框
          // 当删除购物车中的商品数据成功的时候，需要做两件事
          // 1. 隐藏弹出来的对话框 2. 页面应该要显示剩下的商品数(刷新 一般要重新刷新页面重发请求)
          this.cartInfoList = this.cartInfoList.filter(cartInfo => cartInfo.skuId !== this.skuId);
        } else {
          console.log(result.message);
        }
        return; // 不要再往下执行了
      }

      const result = await reqDelSelectedCartInfo(this.skuIdList);
      console.log('delSelected', result);
      if (result.code === 200) {
        this.visible = false; // 关闭对话框
        this.cartInfoList = this.leftCartInfoList;
      } else {
        console.log(result.message);
      }
    },
    // 4. 单击批量删除按键时弹出对话框
    showDialogByDelSelected() {
      // 4.0 清空数组
      this.skuIdList = [];
      this.leftCartInfoList = [];
      // 4.1 弹出对话框
      this.visible = true;
      // 4.2 收集被选中的商品的id
      this.cartInfoList.forEach(cartInfo => {
        // if(cartInfo.isChecked===1){
        if (cartInfo.isChecked) {
          this.skuIdList.push(cartInfo.skuId);
        } else {
          this.leftCartInfoList.push(cartInfo);
        }
      });

      // 4.3 区分批量删除
      this.isDelOne = false;
    },
    // async changeSkuNum(type, cartInfo, e) {
    //   let num = 0
    //   let { skuId, skuNum } = cartInfo
    //   switch (type) {
    //     case 'decrement':
    //       if (cartInfo.skuNum > 1) {
    //         cartInfo.skuNum--
    //         num--
    //       }
    //       break
    //     case 'increment':
    //       if (cartInfo.skuNum < 200) {
    //         cartInfo.skuNum++
    //         num++
    //       }

    //       break
    //     case 'change':
    //       let newSkuNum = e.target.value
    //       if (skuNumReg.test(newSkuNum)) {
    //         num = newSkuNum - cartInfo.skuNum
    //         cartInfo.skuNum = newSkuNum
    //         if (newSkuNum > 200) {
    //           num = 200 - cartInfo.skuNum
    //           cartInfo.skuNum = 200
    //         }
    //       } else {
    //         // cartInfo.skuNum = 1
    //         e.target.value = cartInfo.skuNum
    //       }
    //       break
    //   }

    //   if (num == 0  ) return
    //   const result = await reqAddOrUpdateCart(skuId, num)
    // },
    // 6. 更改购物车中商品的数据
    changeSkuNum(type, cartInfo, e) {
      if (this.timeId) clearTimeout(this.timeId);
      // if(type==='increment'){

      // }else if(type ==='decrement'){

      // }
      // let num = 0; // 定义一个初始值
      let oldNum = cartInfo.skuNum;   //101
      switch (type) {
        case 'increment':
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++;
            // num++;
            this.num++;
          }
          break;
        case 'decrement':
          if (cartInfo.skuNum > 1) {
            cartInfo.skuNum--;
            // num--;
            this.num--;
          }
          break;
        case 'change':
          // 获取新输入的值
          let newNum = e.target.value;
          if (skuNumReg.test(newNum)) {
            cartInfo.skuNum = newNum;
            // num = newNum - oldNum; // 更改后的插值
            this.num = newNum - oldNum;
            // 当用户更改的数量大于200的时候，最大值只能是200
            if (newNum > 200) {
              cartInfo.skuNum = 200;
              // num = 200 - oldNum;
              this.num = 200 - oldNum;
            }
          } else {
            // console.log('不满足条件...')
            // cartInfo.skuNum = oldNum // 这样不生效
            e.target.value = oldNum; // 使用这种方式来恢复页面原来的数据
          }
          break;
      }
      // if (num === 0) return; // 如果没有真正的数据更新 则不需要去发送请求
      if (this.num === 0) return;
      // const result = await reqAddOrUpdateSkuInfoToShopCart(cartInfo.skuId, num);
      this.timeId = setTimeout(async () => {
        const result = await reqAddOrUpdateCart(cartInfo.skuId, this.num);
        // console.log(result)
        if (result.code === 200) {
          // 后期可以加入element-ui框架中的提示功能
          this.num = 0; 
          this.$message({
            type: 'success',
            message: '数据更新成功...'
          });
        } else {
          console.log(result.message);
        }
      }, 700);
    }
  },
  computed: {
    // 1. 实现全选 全不选
    checkAll: {
      get() {
        return this.cartInfoList.every(cartInfo => cartInfo.isChecked === 1) && this.cartInfoList.length;
      },
      async set(val) {
        let isChecked = val ? 1 : 0;
        const skuIdList = [];
        this.cartInfoList.forEach(item => {
          item.isChecked = isChecked;

          skuIdList.push(item.skuId);
        });
        // 统一批量更新选中状态
        const result = await reqChangeAllCartState(isChecked, skuIdList);
        if (result.code === 200) {
          alert('更新成功...');
        } else {
          console.log('更新失败...');
        }
      }
    },
    // 2. 已选商品个数
    selectedCount() {
      return this.cartInfoList.reduce((prev, current) => prev + current.isChecked, 0);
    },
    // 3. 统计总金额
    selectedMoney() {
      return this.cartInfoList.reduce((prev, current) => prev + current.isChecked * current.skuPrice * current.skuNum, 0);
    }
  },
  watch: {
    visible: {
      immediate: true, // 一开始立即就监视
      handler() {
        if (this.visible) {
          document.documentElement.style.overflow = 'hidden';
        } else {
          document.documentElement.style.overflow = 'auto';
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
  .btn-footer {
    position: absolute;
    right: 2px;
    bottom: 20px;
    .btn {
      width: 70px;
      height: 40px;
      border: none;
      border-radius: 6px;
      margin-right: 20px;
      cursor: pointer;
    }
    .btn-primary {
      color: #fff;
      background-color: #409eff;
      &:hover {
        background-color: #66b1ff;
      }
    }
    .btn-cancle {
      border: 1px soild #ccc;
      &:hover {
        background-color: #ecf5ff;
        color: #66b1ff;
      }
    }
  }
}
</style>